package com.tuomaxu.dao.impl;

import com.tuomaxu.annotation.Autowired;
import com.tuomaxu.annotation.Component;
import com.tuomaxu.dao.AccountDao;
import com.tuomaxu.pojo.Account;
import com.tuomaxu.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Component("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;


    @Override
    public Account queryAccountByCId(Integer id) throws Exception {
//        DruidDataSource druidDataSource = DruidUtils.getInstance();
//        Connection connection = druidDataSource.getConnection();
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "select * from account where id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        account.setId(id);

        while (resultSet.next()){
            String name = resultSet.getString("name");
            Integer money = resultSet.getInt("money");

            account.setName(name);
            account.setMoney(money);

        }

        resultSet.close();
        preparedStatement.close();
//        connection.close();

        return account;
    }

    @Override
    public int updateAccount(Account account) throws Exception {
//        DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "update account set money=? where id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setInt(2,account.getId());

        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
//        connection.close();
        return 0;
    }
}
